<template>
  <div class="data">
    <h2>数据管理</h2>
    
    <!-- 添加上传组件 -->
    <el-upload
      class="upload-demo"
      :http-request="customUpload"
      :show-file-list="true"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">支持上传所有类型文件</div>
    </el-upload>
  </div>
</template>

<script>
import ObsClient from 'esdk-obs-browserjs'

export default {
  name: 'DataManage',
  
  data() {
    return {
      obs: null
    }
  },

  created() {
    // 初始化 OBS 客户端
    this.obs = new ObsClient({
      access_key_id: 'BHNNDLCKS8SKNMFVBPTS',      
      secret_access_key: 'kWTcUtr2QUWShoRBGtelQjTlsqBaOqYUQe9z9R2n',      
      server: 'https://obs.cn-southwest-2.myhuaweicloud.com'
    })

    // 输出 OBS 客户端配置
    console.log('OBS 客户端配置:', {
      access_key_id: this.obs.access_key_id,
      server: this.obs.server,
      is_initialized: !!this.obs
    })
    console.log('完整的 OBS 客户端:', this.obs)

    // 先检查桶是否存在
    this.obs.headBucket({
      Bucket: 'test-mlcoc'
    }).then(result => {
      console.log('桶存在:', result)
      // 桶存在，直接设置 CORS
      this.setCors()
    }).catch(err => {
      console.error('检查桶失败:', err)
    })
  },

  methods: {
    // 自定义上传
    async customUpload({ file }) {
      try {
        const result = await this.obs.putObject({
          Bucket: 'test-mlcoc',
          Key: `uploads/${file.name}`,
          SourceFile: file,
          ContentType: file.type,
          Metadata: {
            'x-obs-meta-filetype': file.type
          }
        })

        if (result.CommonMsg.Status === 200) {
          this.$message.success('上传成功')
          const fileUrl = `https://${result.BucketName}.obs.cn-southwest-2.myhuaweicloud.com/${result.Key}`
          console.log('文件地址：', fileUrl)
        } else {
          this.$message.error('上传失败')
        }
      } catch (error) {
        console.error('上传错误：', error)
        this.$message.error('上传失败：' + error.message)
      }
    },

    // 单独封装 CORS 设置方法
    async setCors() {
      try {
        const result = await this.obs.setBucketCors({
          Bucket: 'test-mlcoc',
          CORSRule: [
            {
              AllowedOrigin: ['*'],
              AllowedMethod: ['GET', 'PUT', 'POST', 'DELETE', 'HEAD'],
              AllowedHeader: ['*'],
              ExposeHeader: ['ETag'],
              MaxAgeSeconds: 3600
            }
          ]
        })
        console.log('CORS 设置结果:', result)
      } catch (error) {
        console.error('CORS 设置详细错误:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.data {
  padding: 20px;
}

.upload-demo {
  margin: 20px 0;
}
</style> 